// pages/index/place-order-entity/place-order-entity.js
import Dialog from '../../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'

let app = getApp();
const moment = require('../../../utils/moment.min.js')
const util = require('../../../utils/dateUtils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    shop: '',
    order: null,
    products: null,
    isDisabled: false,//控制"提交订单"
    goods_express: [],//快递商品
    goods_nextDay: [],//团购商品
    isCoupon: false,//优惠卷弹框
    couponsList: [],//可用优惠卷
    couponId: '',//优惠卷id
    discountPrice: 0,//优惠卷抵扣金额
    totalPrice: 0,//商品金额
    payPrice: 0,//总金额
    allFirstPrice: 0,//总运费
    allWeight: 0,//总重量
    dispatchId: 0,//运费数据模板id
    remark: '',//订单备注
    futureName: '',//预约人姓名
    futureMobile: '',//预约人电话
    futureDate: '',//预约时间
    isFutureDate: '',//预约时间弹框
    nowDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date(2019, 10, 1).getTime(),
    minHour: 10,
    maxHour: 20,
    isSubmit: false,

    isSpellgroup: '',//拼团标识
    promoter: '',//发起人id
    sgorderId: '',//发起人订单号
  },

  getPrecreate() {
    let _this = this;
    let syncOrder = JSON.parse(wx.getStorageSync('order'));
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/order/precreate',
      data: {
        memberId: _this.data.user.id,
        products: syncOrder.cartItems,
        isSpellgroup: _this.data.isSpellgroup,
        orderId: _this.data.sgorderId,
      },
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': wx.getStorageSync('authToken') || 'empty-token'
      },
      load: 1
    }).then((res) => {
      if (res.data.code == 500) {
        Dialog.alert({
          title: '提示',
          message: res.data.msg
        }).then(() => {
          wx.navigateBack({ detail: 1 })
        })
        return;
      }
      let productsData = res.data.data;

      _this.data.couponsList = res.data.coupons || [];//可用优惠券
      _this.setData({
        couponsList: _this.data.couponsList,
        couponId: _this.data.couponsList.length > 0 ? _this.data.couponsList[0].id : ''
      })

      if (res.data.overtime) {
        Dialog.alert({
          message: '部分商品没有开团，请删除没开团商品再提交订单'
        }).then(() => {
          _this.setData({
            isDisabled: true
          })
        });
      }
      if (res.data.limit) {
        Dialog.alert({
          message: '部分批发商品购买数量小于最低购买数量'
        }).then(() => {
          _this.setData({
            isDisabled: true
          })
        });
      }

      _this.onHandle(productsData);
    })
  },

  //逻辑处理
  onHandle(data) {
    let _this = this;
    let syncOrder = JSON.parse(wx.getStorageSync('order'));
    let assistMode = wx.getStorageSync('assistMode')// 1 代下单模式

    //用户信息、门店信息
    let tempOrder = {
      mid: _this.data.user.id,
      realname: _this.data.user.realname ? _this.data.user.realname : "",
      nickname: _this.data.user.nickname,
      mobile: _this.data.user.mobile,
      sname: assistMode ? '' : (_this.data.user.realname || _this.data.user.nickname),
      saddress: _this.data.user.address,
      shopName: _this.data.shop && _this.data.shop.realname ? _this.data.shop.realname : '',
      shopMobile: _this.data.shop && _this.data.shop.mobile ? _this.data.shop.mobile : '',
      shopXiaoqu: _this.data.shop ? _this.data.shop.tXiaoqu : _this.data.user.province + ' ' + _this.data.user.city + ' ' + _this.data.user.area + ' ' + _this.data.user.address + ' ' +
        _this.data.user.xiaoqu,
      shopAddress: _this.data.shop ? (_this.data.shop.tProvince + _this.data.shop.tCity + _this.data.shop.tArea + _this.data.shop.tXiaoqu + _this.data.shop.tShopname) : '',
    }

    let tempGoods = [];
    data.forEach(goods => {
      goods.productId = goods.id;
      for (let i = 0; i < syncOrder.cartItems.length; ++i) {
        let cartItem = syncOrder.cartItems[i];
        if (cartItem.productId === goods.id && !cartItem.findGoods) {
          goods.total = cartItem.total || 1;
          goods.cartId = cartItem.cartId;

          if (cartItem.skuId) {
            goods.skuId = cartItem.skuId;
            goods.optionname = cartItem.skuTitle;
            goods.marketprice = cartItem.marketprice;
            goods.vipprice = cartItem.vipprice;
          }
          cartItem.findGoods = true; //用于同一商品多规格时的判断
          break;
        }
      }
      tempGoods.push(goods);
    })

    //处理数据
    _this.onDifferentiate(tempGoods);
    //商品金额
    _this.totalPriceFun();
    //优惠卷抵扣金额
    _this.discountPriceFun();

    _this.setData({
      order: tempOrder,
      products: tempGoods,
    })

  },

  //区分数据，团购/快递
  onDifferentiate(i) {
    let _this = this;
    _this.setData({
      goods_express: [],
      goods_nextDay: [],
    })
    i.forEach((goods, i) => {
      goods.picArr = [];
      goods.prodlabels.split(",").forEach(item => {
        if (item) goods.picArr.push(item);
      })
      if (goods.isKuaidi == 1) {
        _this.data.goods_express.push(goods);
      } else {
        _this.data.goods_nextDay.push(goods);
      }
    });
    _this.setData({
      goods_express: _this.data.goods_express,
      goods_nextDay: _this.data.goods_nextDay,
    })

    //计算邮费
    _this.getDispatchList();

  },

  //计算商品金额
  totalPriceFun() {
    let _this = this;
    let tempPrice = 0;
    if (_this.data.goods_express.length > 0) {
      _this.data.goods_express.reduce((total, item) => {
        tempPrice += (_this.data.user.isVip && item.vipprice && item.isvip && _this.data.user.vipofcentreId.indexOf(_this.data.user.centreId) != -1) ? item.vipprice * item.total : item.marketprice * item.total
      }, 0)
    }
    else {
      _this.data.goods_nextDay.reduce((total, item) => {
        tempPrice += (_this.data.user.isVip && item.vipprice && item.isvip && _this.data.user.vipofcentreId.indexOf(_this.data.user.centreId) != -1) ? item.vipprice * item.total : item.marketprice * item.total
      }, 0)
    }

    _this.setData({
      totalPrice: parseFloat(tempPrice).toFixed(2)
    })
    this.payPriceFun();
  },

  //计算邮费
  getDispatchList() {
    let _this = this;
    if (_this.data.goods_express.length <= 0) return;

    let dispatchListTemp = []//所有数据
    let dispatchList = [];//calculatetype=3通用数据
    let dispatchId = "";//数据模板id
    let allWeight = 0;//总重量
    let allFirstPrice = 0;//总运费

    let postage = _this.data.goods_express.map(item => {
      if (item.isbig == 0) {//不包邮
        return {
          isKuaidi: item.isKuaidi,//0团购，1直发
          weight: item.weight,//重量
        }
      } else if (item.isbig == 1) {//包邮
        console.log('包邮')
      }

    });

    if (postage) {
      //得到总重量
      postage.forEach(item => {
        if (item) {
          console.log('循环计算总重量：' + item.weight)
          allWeight += parseInt(item.weight);
        } else {
          console.log('循环包邮')
        }
      });
    }

    app.requestUrl({
      method: 'POST',
      url: '/wxapi/getDispatchList',
    }).then((res) => {
      dispatchListTemp = res.data.data;

      dispatchListTemp.forEach(dispatchTemp => {
        if (dispatchTemp.calculatetype == 3) {//calculatetype=3通用
          dispatchId = dispatchTemp.id;//数据id
          allFirstPrice = dispatchTemp.firstprice;//起始运费
          return;
        }
      });

      dispatchListTemp.forEach(dispatchTemp => {
        if (dispatchTemp.parentId == dispatchId) {
          dispatchList.push(dispatchTemp)
        }
      });
      var isReturn = true;
      dispatchList.forEach(dispatch => {
        //calculatetype=2包邮
        //总价格大于后端配置价格，取当前数据运费，结束循环
        if (dispatch.calculatetype == 2 && _this.payPriceTemp() >= dispatch.firstweight) {
          dispatchId = dispatch.id;
          allFirstPrice = dispatch.firstprice;
          allWeight = 0;
          console.log("总价格大于后端配置价格，取当前数据运费_this.payPriceTemp=" + _this.payPriceTemp());
          isReturn = false;
        }
        //订单总重量在后端配置之间，取当前数据运费
        if (isReturn && allWeight >= dispatch.firstweight && allWeight <= dispatch.secondweight) {
          dispatchId = dispatch.id;
          allFirstPrice = dispatch.firstprice;
          console.log("订单总重量在后端配置之间，取当前数据运费");
        }
      });
      _this.setData({
        allFirstPrice: allFirstPrice,
        allWeight: allWeight,
        dispatchId: dispatchId
      })
      this.payPriceFun();
    })
  },

  //商品总价-优惠卷抵扣
  payPriceTemp() {
    let _this = this;
    return Math.max(_this.data.totalPrice - this.data.discountPrice, 0);
  },

  //总金额
  payPriceFun() {
    let _this = this;
    let count = parseFloat(_this.data.totalPrice) + parseFloat(_this.data.allFirstPrice) - parseFloat(_this.data.discountPrice)
    count = parseFloat(parseFloat(count).toFixed(2));
    _this.setData({
      payPrice: Math.max(count, 0)
    })
  },

  //提交订单表达验证
  onSubmitFever() {
    let _this = this;

    //非预约订单，并且非餐饮订单，显示收货地址，需要校验是否正确
    //餐饮订单，外卖类型，显示收货地址，需要校验是否正确
    if (_this.data.products[0].productType != 4 && this.data.productType != 6 || this.data.productType == 6 && this.data.cateringType == '2') {
      if (!_this.data.order.sname || !_this.data.order.mobile || !(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(_this.data.order.mobile))) {
        wx.showToast({
          title: "请填写正确的取货人姓名和电话",
          icon: 'none',
          duration: 3000,
        })
        return;
      }

      // if (!_this.data.user.address && _this.data.goods_nextDay == '') {
      //   wx.showToast({
      //     title: "请完善快递直发收货地址",
      //     icon: 'none',
      //     duration: 3000,
      //   })
      //   return;
      // }
    }

    if (_this.data.shop) {
      let checkShop = app.checkShop();
      if (checkShop != 1 && _this.data.goods_nextDay != '') {
        Dialog.alert({
          message: '当前门店已经关闭或者打烊中，请选择其他门店进行下单'
        }).then(() => {
          wx.switchTab({
            url: '/pages/index/index',
          })
        });
        return;
      }
    }

    //预约订单或者到店自提的外卖订单，需要填入预约相关信息
    if (_this.data.products[0].productType == 4 || this.data.productType == 6 && this.data.cateringType == '3') {
      //只有预约订单，才会有预约人姓名
      if (!_this.data.futureName && _this.data.products[0].productType == 4) {
        wx.showToast({ title: "请填写预约人姓名", icon: 'none', duration: 3000 })
        return;
      } else if (!_this.data.futureMobile) {
        wx.showToast({ title: "请填写预约人姓名", icon: 'none', duration: 3000 })
        return;
      } else if (!_this.data.futureDate) {
        wx.showToast({ title: "选择预约人到店时间", icon: 'none', duration: 3000 })
        return;
      }
    }

    if (_this.data.goods_nextDay.length > 0) {
      Dialog.confirm({
        title: '确认下单',
        message: '请确认提货地址：' + _this.data.order.shopXiaoqu
      }).then(() => {
        _this.onSubmitReq();
      }).catch(() => { });
    } else {
      _this.onSubmitReq();
    }
  },

  //提交订单接口
  onSubmitReq() {
    let _this = this;
    _this.setData({ isSubmit: true });//按钮开启加载

    // wx.requestSubscribeMessage({
    //   tmplIds: [app.globalData.subscribeMessage], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
    //   success(res) {
    //    _this.onSubmitReqTwo();
    //   },
    //   fail(res) {
    //     Dialog.confirm({
    //       title: '温馨提示',
    //       message: '已关闭订阅消息，是否前往设置开启订阅消息',
    //       confirmButtonOpenType: 'openSetting'
    //     }).then(() => {
    //       wx.openSetting({
    //         success: (res) => {
    //           _this.setData({ isSubmit: false });
    //         }
    //       })
    //     }).catch(() => {
    //       _this.onSubmitReqTwo();
    //     })
    //   }
    // })
    _this.onSubmitReqTwo();
  },
  onSubmitReqTwo() {
    let _this = this;
    let productsLet = [];
    // 获取座位号
    let tShopId = app.getShop().id;
    let seatNum = wx.getStorageSync("seatNum-" + tShopId);
    _this.data.products.map((item) => {
      productsLet.push({
        id: item.cartId ? (item.cartId.toString().indexOf(':') == -1 ? item.cartId + ':null' : item.cartId) : '',
        productId: item.id,
        total: item.total,
        mid: _this.data.user.id,
        teamid: _this.data.user.upshopTid,
        openid: _this.data.user.openid,
        skuId: item.skuId,
        centreId: item.centreId,
      })
    });
    let params = {
      memberId: _this.data.user.id,
      products: productsLet,
      sname: _this.data.order.sname + (wx.getStorageSync('assistBuy') ? '(代客下单)' : ''),
      mobile: _this.data.order.mobile,
      houseNo: '',
      couponId: _this.data.couponId,//优惠卷id
      Authorization: wx.getStorageSync('authToken'),
      allweight: _this.data.allWeight,//重量
      dispatchprice: _this.data.allFirstPrice,//运费
      dispatchid: _this.data.dispatchId,//数据模板id
      isSpellgroup: _this.data.isSpellgroup,//拼团标识
      promoter: _this.data.promoter,//发起人id
      orderId: _this.data.sgorderId,//发起人订单号
      iscomment: _this.data.remark,//订单备注
      appointmentName: _this.data.futureName,//预约人姓名
      appointmentMobile: _this.data.futureMobile,//预约人电话
      appointmentDate: _this.data.futureDate,//预约时间
      seatNum: seatNum,
      orderType: _this.data.productType,//订单类型，只有外卖订单会传入
      cateringType: _this.data.cateringType //餐饮类型，只有外卖订单才会有值传入
    };

    app.requestUrl({
      method: 'POST',
      url: '/wxapi/order/create',
      data: params,
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': wx.getStorageSync('authToken') || 'empty-token'
      },
      load: 1
    }).then((res) => {
      if (res.data.success) {
        //减少购物车数量
        productsLet.forEach(product => {
          if (product.id)
            app.globalData.cartTotal -= product.total;//改变购物车数量
        });
        wx.navigateTo({
          url: '/pages/user/order-info/order-info?payId=' + res.data.data
        })
      } else {
        Dialog.alert({
          message: res.data.msg
        })
      }
      _this.setData({ isSubmit: false });//按钮关闭加载
    }).catch(() => {
      _this.setData({ isSubmit: false });//按钮关闭加载
    })
  },

  snameBlur(event) {
    this.setData({
      'order.sname': event.detail.value
    })
  },
  mobileBlur(event) {
    this.setData({
      'order.mobile': event.detail.value
    })
  },
  remarkBlur(event) {
    this.setData({ remark: event.detail.value })
  },
  futureNameBlur(event) {
    this.setData({ futureName: event.detail.value })
  },
  futureMobileBlur(event) {
    this.setData({ futureMobile: event.detail.value })
  },


  //不使用优惠卷，-1不使用优惠卷
  onCancelCoupon() {
    this.setData({
      isCoupon: false,
      couponId: -1
    })
    this.discountPriceFun();
  },
  //使用优惠卷
  onSubmitCoupon() {
    let _this = this;
    _this.setData({
      isCoupon: false,
      couponId: _this.data.couponId == -1 ? -1 : _this.data.couponId
    })
    _this.discountPriceFun();
  },
  //优惠卷选择
  couponChange(event) {
    let _this = this;
    _this.setData({
      couponId: event.detail
    })
  },
  //点击打开优惠卷弹框
  isCouponClick() {
    let _this = this;
    if (_this.data.couponsList.length == 0) return;
    this.setData({
      isCoupon: true,
      couponId: _this.data.couponId == -1 ? -1 : _this.data.couponsList[0].id,//默认选择第一张优惠卷
    })
  },
  //优惠劵抵扣金额
  discountPriceFun() {
    let _this = this;
    //不使用优惠卷
    if (_this.data.couponId != '' && _this.data.couponId != -1) {
      _this.data.couponsList.filter(item => {
        if (_this.data.couponId == item.id) {
          if (item.type === 1)
            _this.setData({
              discountPrice: item.amount
            })
          else
            _this.setData({
              discountPrice: item.amount * _this.data.totalPrice / 100
            })
        }
      });
    } else if (_this.data.couponsList.length > 0) {
      _this.setData({
        discountPrice: 0
      })
    }
    _this.payPriceFun();
  },

  //预约时间
  futureDateMonitor() {
    let _this = this;
    _this.setData({ isFutureDate: !_this.data.isFutureDate })
  },
  futureDateConfirm(event) {
    console.log(event.detail);
    this.setData({
      futureDate: util.formatTimeThree(event.detail / 1000, "Y-M-D h:m:s")
    })
    this.futureDateMonitor();
  },

  //个人资料页面
  toSetting() {
    wx.navigateTo({
      url: '/sub/user/setting/setting?isAll=1'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    this.setData({
      isSpellgroup: event.isSpellgroup || '',//拼团标识
      promoter: event.promoter,//发起人id
      sgorderId: event.sgorderId || '',//发起人订单号
      productType: event.productType || '',//订单和产品类型
      cateringType: event.cateringType || '',//餐饮类型，只有在外卖订单中才会出现
      shopInfo: app.getShop()
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    _this.setData({
      user: app.getUser(),
      shop: app.getShop(),
      order: JSON.parse(wx.getStorageSync('order')),
    })

    this.getPrecreate();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
